package com.woniu.service.impl;


import com.woniu.been.entity.Video;
import com.woniu.mapper.VideoMapper;
import com.woniu.service.MinioService;
import com.woniu.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private MinioService minioService;

    @Override
    @Transactional
    public Video saveVideo(Video video) {
        videoMapper.insert(video);
        return video;
    }

    @Override
    public List<Video> getVideosByCourseId(Integer courseId) {
        return videoMapper.findByCourseId(courseId);
    }

    @Override
    @Transactional
    public boolean updateVideoTitle(Integer videoId, String title) {
        return videoMapper.updateTitle(videoId, title) > 0;
    }

    @Override
    @Transactional
    public boolean deleteVideoByFileName(String fileName) {
        try {
            // 先从MinIO删除文件
            minioService.deleteVideo(fileName);
            // 再从数据库删除记录
            return videoMapper.deleteByFileName(fileName) > 0;
        } catch (Exception e) {
            throw new RuntimeException("Failed to delete video from MinIO or database: " + fileName, e);
        }
    }

    @Override
    @Transactional
    public boolean deleteVideosByFileNames(List<String> fileNames) {
        try {
            // 先从MinIO批量删除文件
            minioService.deleteVideos(fileNames);
            // 再从数据库批量删除记录
            for (String fileName : fileNames) {
                videoMapper.deleteByFileName(fileName);
            }
            return true; // 假设MinIO和数据库删除都成功
        } catch (Exception e) {
            throw new RuntimeException("Failed to batch delete videos from MinIO or database.", e);
        }
    }

    @Override
    public Video findVideoByFileName(String fileName) {
        return videoMapper.findByFileName(fileName);
    }

    @Override
    public List<Video> getVideosByCourseIdAndFilters(Integer courseId, String categoryName) {
        return videoMapper.findByCourseIdAndFilters(courseId, categoryName);
    }

    @Override
    public List<Video> getVideosByChapterId(Integer chapterId) {
        return videoMapper.findByChapterId(chapterId);
    }

    @Override
    public List<Video> getVideosBySubCategoryId(Integer subCategoryId) {
        return videoMapper.findBySubCategoryId(subCategoryId);
    }

    @Override
    public List<Video> getVideosByMainCategoryId(Integer mainCategoryId) {
        return videoMapper.findByMainCategoryId(mainCategoryId);
    }
} 